﻿using Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using static ProjectManagerSys.backoffice.project.SetTimeMerber;

namespace ProjectManagerSys
{
    /// <summary>
    /// 时间矩阵算法
    /// </summary>
    public class CalculateMatrixTime
    {

        /// <summary>
        /// 计算因插入任务，其他任务时间有交集的任务的最终结束时间
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="effectA"></param>
        /// <param name="effectB"></param>
        /// <returns></returns>
        public string LastTime(DateTime startTime, int effectA, int effectB,out int index)
        {
            //取出上班安排时间
            string json = JsonFileHelp.ReadJsonFile(Environment.CurrentDirectory + "/appsettings.json", "worktime");
            worktimemodel oTime = JsonConvert.DeserializeObject<worktimemodel>(json);

            var totalNeedMinute = effectA + effectB; //总共需要工时/单位分钟
            
            int endHour = 0, endMinute = 0;  //工作A+B最终结束的时刻
            //上午工作时间段
            Matrix m1 = TimeToMatrix(oTime.morning_start, oTime.morning_end);
            //下午工作时间段(不可和上午重叠)
            m1 += TimeToMatrix(oTime.afternoon_start, oTime.afternoon_end);
            //如果结束时间到达下班时间，矩阵没有有效时长了，所以开始时间应该从早上上班时间开始算
            //if (startTime.Hour >= Convert.ToDateTime(oTime.afternoon_end).Hour)
            //    startTime = Convert.ToDateTime(oTime.morning_start);
            int startHour = startTime.Hour, startMinute = startTime.Minute;  //工作A+B开始的时刻   需设置

            index = 0;   //使用list的下标
            try {
                var isCalculated = false; //是否计算过
                while (totalNeedMinute > 0)
                {
                    //int count = 0;
                    for (int i = 0; i < 24; i++)
                    {
                        for (int j = 0; j < 60; j++)
                        {
                            //根据判断是否已经计算过
                            if (isCalculated)
                            {
                                if (m1[i, j] > 0) //当前时间点为工作日时间
                                {
                                    m1[i, j]++;
                                    totalNeedMinute--;
                                    if (totalNeedMinute == 0)
                                    {
                                        //realDay = m1[i, j] == 2 ? 0 : (int)m1[i, j] - 2;
                                        //realDay = count;
                                        endHour = i;
                                        endMinute = j;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                if (i >= startHour && j >= startMinute && m1[i, j] > 0)
                                {
                                    m1[i, j]++;
                                    totalNeedMinute--;
                                    isCalculated = true;
                                }
                            }
                        }
                    }
                    index += 1;
                    if (index > 0) isCalculated = true;                   
                }
            }
            catch (Exception ex) { }

            return Convert.ToDateTime(endHour+":" + endMinute).AddMinutes(1).ToString("HH:mm");
        }

        /// <summary>
        ///  以一天为时间范围，计算出时间安排的有效工时（未完成验证，请勿使用）
        /// </summary>
        /// <param name="startTimeHM">开始时间的小时分钟（例：00:00）</param>
        /// <param name="endTimeHM">结束时间的小时分钟（例：12:00）</param>
        /// <returns></returns>
        public int effectTime(string startTimeHM,string endTimeHM)
        {
            
            //取出上班安排时间
            string json = JsonFileHelp.ReadJsonFile(Environment.CurrentDirectory + "/appsettings.json", "worktime");
            worktimemodel oTime = JsonConvert.DeserializeObject<worktimemodel>(json);

            //上午工作时间段
            Matrix m1 = TimeToMatrix(oTime.morning_start, oTime.morning_end);
            //下午工作时间段(不可和上午重叠)
            m1 += TimeToMatrix(oTime.afternoon_start, oTime.afternoon_end);
            //实际工作的时间段
            Matrix m2 = TimeToMatrix(startTimeHM, endTimeHM);

            Matrix m3 = m1 + m2; //矩阵相加
            int minute = 0;  //有效工作分钟
            for (int i = 0; i < 24; i++)
            {
                for (int j = 0; j < 60; j++)
                {
                    if (m3[i, j] > 1) //重叠部分
                    {
                        minute++;
                    }
                }
            }

            return (minute);
        }

        static Matrix TimeToMatrix(string strStarTime, string strEndTime, double n = 1)
        {
            Matrix matrix = new Matrix(24, 60);
            matrix.SetValue(0);
            var tempTimeArray = strStarTime.Split(':');
            int hourStar = int.Parse(tempTimeArray[0]);
            int minuteStar = int.Parse(tempTimeArray[1]);
            tempTimeArray = strEndTime.Split(':');
            int hourEnd = int.Parse(tempTimeArray[0]);
            int minuteEnd = int.Parse(tempTimeArray[1]);
            for (int i = hourStar; i <= hourEnd; i++)
            {
                for (int j = 0; j < 60; j++)
                {
                    if (i == hourEnd && j == minuteEnd)
                    {
                        break;
                    }
                    if (i == hourStar && j < minuteStar)
                    {
                        continue;
                    }
                    matrix[i, j] = n;
                }
            }
            return matrix;
        }
    }
}
